CROSS_COMPILE ?= riscv64-linux-gnu-
CC := $(CROSS_COMPILE)gcc

ARCH := rv64
CFLAGS := -march=rv64gc -mabi=lp64 -nostdlib -nostartfiles -ffreestanding -Wall -Wextra -O2 -g
LDFLAGS := -T linker/kernel.ld -nostdlib -ffreestanding

OUT := build
KERNEL_ELF := $(OUT)/kernel.elf

SRCS_C := $(wildcard kernel/*.c)
SRCS_S := $(wildcard boot/*.S)
OBJS := $(patsubst %.c,$(OUT)/%.o,$(SRCS_C)) $(patsubst %.S,$(OUT)/%.o,$(SRCS_S))

all: $(KERNEL_ELF)

$(OUT)/%.o: %.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -I. -c $< -o $@

$(OUT)/%.o: %.S
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -D__ASSEMBLY__ -c $< -o $@

$(KERNEL_ELF): $(OBJS) linker/kernel.ld
	$(CC) $(CFLAGS) -Wl,$(LDFLAGS) -o $@ $(filter %.o,$^)

run: all
	qemu-system-riscv64 -machine virt -nographic -bios /usr/lib/riscv64-linux-gnu/opensbi/generic/fw_jump.elf -kernel $(KERNEL_ELF)

clean:
	rm -rf $(OUT)

.PHONY: all run clean
